/**
 * 权益类资产特征
 * @author muisuidaan
 */
import React, { useEffect, useState } from "react";
import styles from "../FixedAssets/index.less";
import styled from "./index.less";

import cn from "classnames";
import { Table } from "antd";

import * as _ from "lodash";
import {
  find_heavy_warehouse_stock,
  queryStockStyleFeatureChart,
  stock_industry_distribution_sw,
  stock_industry_distribution_zz,
  stock_plate_characteristic,
  query_latest_barra,
  find_by_portfolio_code
} from "./fixedAssets";

import { PageWrapper } from "@/components/PageWrapper";
import { Title } from "@/components/Title";
import { RenderDesc } from "@/pages/FixedAssets/index";
import AssetsCard from "./components/assetsCard";
import EventEmpty from "@/components/FOF/EventEmpty";
import Area from "@/components/EchartsComponents/Area";
import Bar from "@/components/EchartsComponents/Bar/stackBar";
import CustomizeRadio from "@/components/CustomizeRadio";
import LittleTitle from "@/components/Title/littleTitle";
import TreeMap from "./treemap";


import { getUrlParam } from "@/utils/utils";

const portfolioCode = getUrlParam("id");

import { getBaseColors, getExpandColors } from "@/utils/echarts";
import { ColumnsType } from "antd/lib/table";

interface infoProps {
  [key: string | number]: number | string | null;
}
interface VProps {
  key: string; // 与x轴对应的值
  value: number; // y轴对应的值
}

export interface DataProps {
  label: string; // legend对应的中文
  value: VProps[];
}
export interface axisProps {
  xaxis?: Array<string>;
  yaxis?: Array<DataProps>;
}
export interface infoChartProps {
  axis?: axisProps;
  rateAxis?: axisProps;
  predictedAxis?: axisProps;
  styleNames?: Array<infoProps>;
  changeBarraName?: string;
}
export interface infoChartProps2 extends infoChartProps {
  all?:infoChartProps;
  style?:infoChartProps;
  size?:infoChartProps;
}

const outCreditRatingList= [
  {
    "name": "AAA",
    "num": 20139,
    "value": 52.44
  },
  {
    "name": "AA+",
    "num": 11135,
    "value": 28.99
  },
  {
    "name": "AA",
    "num": 6471,
    "value": 16.85
  },
  {
    "name": "A",
    "num": 152,
    "value": 0.4
  },
  {
    "name": "AA-",
    "num": 142,
    "value": 0.37
  },
  {
    "name": "A+",
    "num": 98,
    "value": 0.26
  },
  {
    "name": "C",
    "num": 44,
    "value": 0.11
  },
  {
    "name": "BB",
    "num": 44,
    "value": 0.11
  },
  {
    "name": "A-",
    "num": 39,
    "value": 0.1
  },
  {
    "name": "B",
    "num": 33,
    "value": 0.09
  },
  {
    "name": "BBB",
    "num": 33,
    "value": 0.09
  },
  {
    "name": "BBB+",
    "num": 25,
    "value": 0.07
  },
  {
    "name": "CC",
    "num": 21,
    "value": 0.05
  },
  {
    "name": "BBB-",
    "num": 15,
    "value": 0.04
  },
  {
    "name": "CCC",
    "num": 6,
    "value": 0.02
  },
  {
    "name": "B+",
    "num": 5,
    "value": 0.01
  },
  {
    "name": "BB+",
    "num": 5,
    "value": 0.01
  }
]
const info_list = [
  {
    key: 3,
    eventCode: "portfolio_section_concentration_zz",
    eventName: "股票所属板块特征",
    littleName:
      "（板块配置比例统计的是单一板块比例占股票总资产的比例。板块分类定义为东海自定义分类。）",
    type: "area",
    kind: "1",
  },
  {
    key: 1,
    eventCode: "portfolio_industry_concentration_sw",
    eventName: "股票行业分布（申万）",
    type: "area",
    kind: "1",
  },
  {
    key: 2,
    eventCode: "portfolio_industry_concentration_zz",
    eventName: "股票行业分布（中证）",
    type: "area",
    kind: "1",
  },

  {
    key: 4,
    eventCode: "stock_style_seatureChart",
    eventName: "股票风格特征",
    type: "area",
    kind: "2",
  },
  {
    key: 5,
    eventCode: "stock_new_",
    eventName: "最新一期持仓股票的因子值监控",
    type: "bar",
    kind: "2",
  },
];

// 分位选项
const quantileOptions = [
  { label: "全部", value: 1 },
  { label: "只看市值", value: 2 },
  { label: "只看风格", value: 3 }
];

const StockFixedAssets = (props: any) => {
  // console.log(props);

  const [detailList, setDetailList] = useState([]);

  const [tabList, setTabList] = useState([...info_list]); //展示项
  const [stockFeatureInfo, setStockFeatureInfo] = useState<infoChartProps2>({}); //股票风格特征
  const [stockIndustryInfoSW, setStockIndustryInfoSW] = useState<axisProps>({}); //股票行业分布（申万）-堆积图
  const [stockIndustryInfoZZ, setStockIndustryInfoZZ] = useState<axisProps>({}); //股票行业分布（中证）-堆积图
  const [stockPlatecharacteristic, setStockPlatecharacteristic] = useState<
    axisProps
  >({}); //股票所属板块特征--堆积图

  const [hasRequest, setHasRuquest] = useState(false);
  const [stockSupervisory, setStockSupervisory] = useState<infoChartProps>({}); //最新一期持仓股票的因子值监控

  const [quantile, setQuantile] = useState(1);

  const [treeMapData,setTreeMapData] = useState([]);

  const [loading1,setLoading1] = useState(true);
  const [loading2,setLoading2] = useState(true);
  const [loading3,setLoading3] = useState(true);
  const [loading4,setLoading4] = useState(true);
  const [loading5,setLoading5] = useState(true);
  const [loading6,setLoading6] = useState(true);
  const [loading7,setLoading7] = useState(true);
  const [loading8,setLoading8] = useState(true);
  const [loading9,setLoading9] = useState(true);
  const [loading10,setLoading10] = useState(true);


  useEffect(() => {
    getData(); //请求完成渲染完成再进行定位
  }, []);


  useEffect(()=>{
    if(!loading7&&!loading2&&!loading3&&!loading1&&!loading4&&!loading5&&!loading6){
      setHasRuquest(true);
    }
  },[loading7,loading2,loading3,loading1,loading4,loading5,loading6])

  const getData = async () => {
    setHasRuquest(false);
    find_by_portfolio_code({
      portfolioCode: portfolioCode,
    }).then(res7=>{
      if (res7.code === "0" && res7.data) {
        setTreeMapData(res7.data?.length>0?res7.data.map((item)=>({name:item?.concept,value:item?.ria})):[]);
      } else {
        setTreeMapData([]);
      }
      setLoading7(false);
    })

    

    //股票风格特征
    queryStockStyleFeatureChart({
      portfolioCode: portfolioCode,
    }).then(res2=>{
      if (res2.code === "0" && res2.data) {
        setStockFeatureInfo(res2.data);
      } else {
        setStockFeatureInfo({});
      }
      setLoading2(false);
    });
   

    //底层持仓明细
    find_heavy_warehouse_stock({
      portfolioCode: portfolioCode,
    }).then(res3=>{
      if (res3.code === "0" && res3.data?.length > 0) {
        setDetailList(res3.data);
      } else {
        setDetailList([]);
      }
      setLoading3(false);
    });
    

    //股票行业分布（申万）-堆积图
    stock_industry_distribution_sw({
      portfolioCode: portfolioCode,
    }).then(res1=>{
      if (res1.code === "0" && res1.data) {
        setStockIndustryInfoSW(res1.data);
      } else {
        setStockIndustryInfoSW({});
      }
      setLoading1(false);
    });
    

    //股票行业分布（中证）-堆积图
    stock_industry_distribution_zz({
      portfolioCode: portfolioCode,
    }).then(res4=>{
      if (res4.code === "0" && res4.data) {
        setStockIndustryInfoZZ(res4.data);
      } else {
        setStockIndustryInfoZZ({});
      }
      setLoading4(false);
    });
    

    //股票所属板块特征--堆积图
    stock_plate_characteristic({
      portfolioCode: portfolioCode,
    }).then(res5=>{
      if (res5.code === "0" && res5.data) {
        setStockPlatecharacteristic(res5.data);
      } else {
        setStockPlatecharacteristic({});
      }
      setLoading5(false);
    });
    
    //股票所属板块特征--堆积图
    query_latest_barra({
      portfolioCode: portfolioCode,
    }).then(res6=>{
      if (res6.code === "0" && res6.data) {
        setStockSupervisory(res6.data);
      } else {
        setStockSupervisory({});
      }
      setLoading6(false);
    });
    
    
  };

  const detailColumns: ColumnsType = [
    {
      title: "序号",
      dataIndex: "",
      key: "",
      width: "50",
      align: "center",
      render: (text, records, index: number) => index + 1,
      // <span
      //   style={{
      //     textAlign: "center",
      //     display: "inline-block",
      //     width: "100%",
      //   }}
      // >
      //   {index + 1}
      // </span>
    },
    {
      title: "股票代码",
      dataIndex: "secuCode",
      key: "secuCode",
      render: (text: string) => text || "-",
      width: "10%",
    },
    {
      title: "股票名称",
      dataIndex: "secuAbbr",
      key: "secuAbbr",
      render: (text: string) => text || "-",
      width: "10%",
    },
    {
      title: "中证行业",
      dataIndex: "zzIndustry",
      key: "zzIndustry",
      render: (text: string) => text || "-",
      width: "10%",
    },
    {
      title: "申万行业",
      dataIndex: "industry",
      key: "industry",
      render: (text: string) => text || "-",
      width: "10%",
    },
    {
      title: "所属板块",
      dataIndex: "plateName",
      key: "plateName",
      width: "10%",
      render: (text: string) => text || "-",
    },
    {
      title: "占基金组合资产净值比例(％)",
      dataIndex: "ratioInnv",
      key: "ratioInnv",
      render: (text: number) => {
        return text || text === 0 ? (text * 100).toFixed(2) : "-";
      },
      width: "22%",
      align:'right'
    },
    {
      title: "持有该股票的基金",
      dataIndex: "positionFunds",
      key: "positionFunds",
      width: "45%",
      render: (text: Array<infoProps>) => {
        return (
          <span
            // style={{display:'inline-block',lineHeight:'20px'}}
            title={
              text?.length > 0
                ? text
                    .map(
                      (item: infoProps) =>
                        `${item.secuAbbr?.toLocaleString() || "-"}(${
                          item.secuCode || "-"
                        })`
                    )
                    .join("，")
                : "-"
            }
          >
            {text?.length > 0
              ? text
                  .map(
                    (item: infoProps) =>
                      `${item.secuAbbr?.toLocaleString() || "-"}(${
                        item.secuCode || "-"
                      })`
                  )
                  .join("，")
              : "-"}
          </span>
        );
      },
      ellipsis: { showTile: true } as boolean | { showTitle?: boolean },
    },
  ];

  return (
    <PageWrapper narrow scrollY minWidth="1068px">
      <Title style={{ marginLeft: 16, marginBottom: 12 }}>权益类资产特征</Title>
      <RenderDesc />
      <div className={cn(styles.holderDetail, styles.mt12)}>
        <LittleTitle title="权益类资产特征-底层重仓股票" />
        <div
          className={cn(
            "list_table_with_border table_header_center compact_table table_outer_border",
            styled.cus_fix_table
          )}
        >
          <Table
            // className="list_table_with_border table_header_center"
            columns={detailColumns}
            dataSource={detailList}
            pagination={false}
            // scroll={{ y: 308 }}
            // scroll={{ x: true }}
            rowKey={(record: any) => record.secuCode}
          />
        </div>
        <div style={{display:'flex'}}>
          <LittleTitle title="股票主要概念分布图" />
          <p className={styled.little_name_text}>（图表仅展示主要市场概念）</p>
        
      </div>
        
        <div className={styled.tree_map_container}>
          {treeMapData?.length>0?<TreeMap
            title=""
            data={treeMapData}
            className="rating-treemap-credit-inner"
            idName="rating-treemap-city-inner"
            percent={true}
            propStyles={{width:'100%',height:'100%',opacity:0.9}}
            // style={{ marginRight: 10 }}
          />:<div className={styled.no_data}>
              <EventEmpty title="暂无数据"></EventEmpty>
            </div>}
        </div>

        {tabList.map((item: infoProps) => {
          return (
            <AssetsCard
              stockHasRequest={hasRequest}
              key={item.key}
              title={item.eventName}
              info={{
                littleName: item.littleName,
                key: item.key,
                eventCode: item.eventCode,
                portfolioCode,
                textMessage:
                  item.key === 4 && stockFeatureInfo?.styleNames?.length > 0
                    ? `<p>组合底层持仓股票的主要风格是 <span>${
                        stockFeatureInfo?.styleNames[0]
                      }</span> ${
                        stockFeatureInfo?.styleNames?.length > 1 ? "和 " : ""
                      }${
                        stockFeatureInfo?.styleNames?.length > 1
                          ? "<span>" +
                            stockFeatureInfo?.styleNames[1] +
                            "</span>"
                          : ""
                      }<span>风格</span></p>`
                    : item.key === 5
                    ? stockSupervisory.changeBarraName
                    : "",
              }}
              kind={item.kind.toLocaleString()}
              children={
                <>
                  {item.type === "area" && item.key === 4 ? (
                    <div>
                      <CustomizeRadio
                        className={cn(styled.radio_container)}
                        label=""
                        options={quantileOptions}
                        value={quantile}
                        setValue={setQuantile}
                      />
                      {stockFeatureInfo?.all?.axis?.xaxis?.length > 0? (
                        <>
                          <div
                            className={styles.chart_echarts}
                            style={{ width: "100%", height: 264 }}
                          >
                            <Area
                              legendStyle={{ top: 5 }}
                              showLine={true}
                              percent={true}
                              idName={`assets-event-detail${item.eventCode}${portfolioCode}1`}
                              xAxis={
                                quantile==1?(stockFeatureInfo?.all?.axis?.xaxis||[]):
                                quantile==2?(stockFeatureInfo?.size?.axis?.xaxis||[]):
                                quantile==3?(stockFeatureInfo?.style?.axis?.xaxis||[]):[]
                              }
                              legend={
                                quantile==1?(stockFeatureInfo?.all?.axis?.yaxis?.length>0?stockFeatureInfo?.all?.axis?.yaxis.map(
                                  (item: DataProps) => item.label
                                )
                              : []):
                                quantile==2?(stockFeatureInfo?.size?.axis?.yaxis?.length>0?stockFeatureInfo?.size?.axis?.yaxis.map(
                                  (item: DataProps) => item.label
                                )
                              : []):
                                quantile==3?(stockFeatureInfo?.style?.axis?.yaxis?.length>0?stockFeatureInfo?.style?.axis?.yaxis.map(
                                  (item: DataProps) => item.label
                                )
                              : []):[]
                                
                              }
                              data={
                                quantile==1?(stockFeatureInfo?.all?.axis?.yaxis||[]):
                                quantile==2?(stockFeatureInfo?.size?.axis?.yaxis||[]):
                                quantile==3?(stockFeatureInfo?.style?.axis?.yaxis||[]):[]
                              }
                              color={[...getBaseColors(), ...getExpandColors()]}
                            />
                          </div>
                        </>
                      ) : (
                        <EventEmpty title="暂无数据"></EventEmpty>
                      )}
                    </div>
                  ) : item.type === "area" &&
                    item.key === 1 &&
                    stockIndustryInfoSW?.xaxis?.length > 0 ? (
                    <div
                      className={styles.chart_echarts}
                      style={{ width: "100%", height: 264 }}
                    >
                      <Area
                        legendStyle={{ top: 5 }}
                        showLine={true}
                        percent={true}
                        idName={`assets-event-detail${item.eventCode}${portfolioCode}1`}
                        xAxis={stockIndustryInfoSW?.xaxis}
                        legend={
                          stockIndustryInfoSW?.yaxis?.length > 0
                            ? stockIndustryInfoSW?.yaxis.map(
                                (item: DataProps) => item.label
                              )
                            : []
                        }
                        data={stockIndustryInfoSW?.yaxis}
                        color={[...getBaseColors(), ...getExpandColors()]}
                      />
                    </div>
                  ) : item.type === "area" &&
                    item.key === 2 &&
                    stockIndustryInfoZZ?.xaxis?.length > 0 ? (
                    <div
                      className={styles.chart_echarts}
                      style={{ width: "100%", height: 264 }}
                    >
                      <Area
                        legendStyle={{ top: 5 }}
                        showLine={true}
                        percent={true}
                        idName={`assets-event-detail${item.eventCode}${portfolioCode}1`}
                        xAxis={stockIndustryInfoZZ?.xaxis}
                        legend={
                          stockIndustryInfoZZ?.yaxis?.length > 0
                            ? stockIndustryInfoZZ?.yaxis.map(
                                (item: DataProps) => item.label
                              )
                            : []
                        }
                        data={stockIndustryInfoZZ?.yaxis}
                        color={[...getBaseColors(), ...getExpandColors()]}
                      />
                    </div>
                  ) : item.type === "area" &&
                    item.key === 3 &&
                    stockPlatecharacteristic?.xaxis?.length > 0 ? (
                    <div
                      className={styles.chart_echarts}
                      style={{ width: "100%", height: 264 }}
                    >
                      <Area
                        // notShowArea
                        legendStyle={{ top: 5 }}
                        showLine={false}
                        percent={true}
                        idName={`assets-event-detail${item.eventCode}${portfolioCode}1`}
                        xAxis={stockPlatecharacteristic?.xaxis}
                        legend={
                          stockPlatecharacteristic?.yaxis?.length > 0
                            ? stockPlatecharacteristic?.yaxis.map(
                                (item: DataProps) => item.label
                              )
                            : []
                        }
                        data={stockPlatecharacteristic?.yaxis}
                        color={[...getBaseColors(), ...getExpandColors()]}
                      />
                    </div>
                  ) : item.type === "area" && item?.key != 4 ? (
                    <EventEmpty title="暂无数据"></EventEmpty>
                  ) : null}

                  {item.type === "bar" &&
                    (stockSupervisory?.axis?.xaxis?.length > 0 ? (
                      <div
                        className={styles.chart_echarts}
                        style={{ width: "100%", height: 264 }}
                      >
                        <Bar
                          legendStyle={{ top: 5 }}
                          isStack={false}
                          // percent={true}
                          idName={`assets-event-detail${item.eventCode}${portfolioCode}1`}
                          xAxis={stockSupervisory?.axis.xaxis}
                          legend={stockSupervisory?.axis.yaxis.map(
                            (item: DataProps) => item.label
                          )}
                          data={stockSupervisory?.axis.yaxis}
                          color={
                            stockSupervisory?.axis.yaxis?.length < 4
                              ? [...getBaseColors(), ...getExpandColors()]
                              : ["#3457C4", "#748295", "#17A785", "#E85C36"]
                          }
                          seriesStyles={{
                            barWidth: 16,
                            barGap: "50%",
                            barMaxWidth: 16,
                          }}
                          gridStyle={{ bottom: 8 }}
                          propsAxisLabelStyle={{ rotate: 0 }}
                        />
                      </div>
                    ) : (
                      <EventEmpty title="暂无数据"></EventEmpty>
                    ))}
                </>
              }
            />
          );
        })}
      </div>
    </PageWrapper>
  );
};

export default StockFixedAssets;
